import { getArea, getLength } from 'ol/sphere';
import Overlay from "ol/Overlay";

export const showTip = (evt, type) => {
    // 绘制的图形的几何信息
    let sketch = evt.feature
    let geom = sketch.getGeometry()

    let result;

    let measureTooltipElement = null;
    let measureTooltip = null;
    let tooltipCoord;

    switch (type) {
        case 'Point':
            break
        case 'LineString':
            result = formatLength(geom)
            tooltipCoord = geom.getLastCoordinate();
            break
        case 'Polygon':
            result = formatArea(geom)
            tooltipCoord = geom.getLastCoordinate();
            break
    }
    let tip = createMeasureTooltip(measureTooltipElement, measureTooltip, result)
    tip.setPosition(tooltipCoord);
    return tip
}

const formatLength = function (line) {
    // 距离
    const length = getLength(line, { projection: "EPSG:4326" });
    let output;
    if (length > 100) {
        output = Math.round((length / 1000) * 100) / 100 + ' ' + 'km';
    } else {
        output = Math.round(length * 100) / 100 + ' ' + 'm';
    }
    return output;
};

const formatArea = function (polygon) {
    // 面积
    const area = getArea(polygon, { projection: "EPSG:4326" });
    let output;
    if (area > 10000) {
        output = Math.round((area / 1000000) * 100) / 100 + ' ' + 'km²';
    } else {
        output = Math.round(area * 100) / 100 + ' ' + 'm²';
    }
    return output;
};

// tip样式
const createMeasureTooltip = (i, tip, result) => {
    if (i) {
        i.parentNode.removeChild(i);
    }
    i = document.createElement('div');
    // css
    i.style.cssText = style;
    i.innerHTML = result
    tip = new Overlay({
        element: i,
        offset: [0, -15],
        positioning: 'bottom-center',
        stopEvent: false,
        insertFirst: false,
    });
    return tip
}

let style = 'position: relative; background: rgba(255, 204, 52, 1);' +
    'border-radius: 4px; color: white; padding: 4px 8px;' +
    'opacity: 1; white-space: nowrap; font-size: 12px;' +
    'cursor: default; user-select: none;'
